# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-04 23:31
# File     : project_routes.py
# Project  : codebuddy_craft
# Desc     : 项目管理接口

# backend/api/project_routes.py
from typing import Dict, List, Optional, Any
from fastapi import APIRouter, HTTPException, Depends, UploadFile, File
from pydantic import BaseModel, Field

from backend.core.services.project_service import (
    project_service, 
    ProjectCreateRequest, 
    ProjectResponse
)
from backend.utils.security import get_current_user_id


router = APIRouter()


class FileCreateRequest(BaseModel):
    """文件创建请求"""
    path: str = Field(description="文件路径")
    content: str = Field(default="", description="文件内容")


class FileSaveRequest(BaseModel):
    """文件保存请求"""
    content: str = Field(description="文件内容")


@router.post("", response_model=Dict[str, Any])
async def create_project(
    request: ProjectCreateRequest,
    user_id: str = Depends(get_current_user_id)
):
    """创建新项目"""
    try:
        result = await project_service.create_project(request, user_id)
        
        return {
            "code": 200,
            "msg": "成功",
            "data": {
                "project_id": result.id,
                "name": result.name,
                "type": result.type,
                "tech_stack": result.tech_stack,
                "created_at": result.created_at.isoformat()
            }
        }
    
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail={
                "code": 50001,
                "msg": f"创建项目失败: {str(e)}",
                "data": None
            }
        )


@router.get("", response_model=Dict[str, Any])
async def list_projects(
    page: int = 1,
    size: int = 10,
    user_id: str = Depends(get_current_user_id)
):
    """获取项目列表"""
    try:
        result = await project_service.list_projects(
            user_id=user_id,
            page=page,
            size=size
        )
        
        return {
            "code": 200,
            "msg": "成功",
            "data": {
                "projects": [
                    {
                        "id": p.id,
                        "name": p.name,
                        "type": p.type,
                        "tech_stack": p.tech_stack,
                        "description": p.description,
                        "file_count": p.file_count,
                        "created_at": p.created_at.isoformat(),
                        "updated_at": p.updated_at.isoformat()
                    }
                    for p in result["projects"]
                ],
                "total": result["total"],
                "page": result["page"],
                "size": result["size"],
                "pages": result["pages"]
            }
        }
    
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail={
                "code": 50001,
                "msg": f"获取项目列表失败: {str(e)}",
                "data": None
            }
        )


@router.get("/{project_id}", response_model=Dict[str, Any])
async def get_project(
    project_id: str,
    user_id: str = Depends(get_current_user_id)
):
    """获取项目详情"""
    try:
        result = await project_service.get_project(project_id, user_id)
        
        return {
            "code": 200,
            "msg": "成功",
            "data": {
                "id": result.id,
                "name": result.name,
                "type": result.type,
                "tech_stack": result.tech_stack,
                "description": result.description,
                "file_count": result.file_count,
                "created_at": result.created_at.isoformat(),
                "updated_at": result.updated_at.isoformat()
            }
        }
    
    except Exception as e:
        raise HTTPException(
            status_code=404 if "不存在" in str(e) else 500,
            detail={
                "code": 40401 if "不存在" in str(e) else 50001,
                "msg": str(e),
                "data": None
            }
        )


@router.get("/{project_id}/files", response_model=Dict[str, Any])
async def get_file_tree(
    project_id: str,
    user_id: str = Depends(get_current_user_id)
):
    """获取项目文件树"""
    try:
        result = await project_service.get_file_tree(project_id, user_id)
        
        def convert_node(node):
            return {
                "name": node.name,
                "path": node.path,
                "type": node.type,
                "size": node.size,
                "children": [convert_node(child) for child in node.children] if node.children else None,
                "created_at": node.created_at.isoformat() if node.created_at else None,
                "updated_at": node.updated_at.isoformat() if node.updated_at else None
            }
        
        return {
            "code": 200,
            "msg": "成功",
            "data": {
                "file_tree": [convert_node(node) for node in result]
            }
        }
    
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail={
                "code": 50001,
                "msg": f"获取文件树失败: {str(e)}",
                "data": None
            }
        )


@router.post("/{project_id}/files", response_model=Dict[str, Any])
async def create_file(
    project_id: str,
    request: FileCreateRequest,
    user_id: str = Depends(get_current_user_id)
):
    """创建文件"""
    try:
        file_id = await project_service.create_file(
            project_id=project_id,
            file_path=request.path,
            content=request.content,
            user_id=user_id
        )
        
        return {
            "code": 200,
            "msg": "创建成功",
            "data": {
                "file_id": file_id,
                "path": request.path
            }
        }
    
    except Exception as e:
        raise HTTPException(
            status_code=400 if "已存在" in str(e) else 500,
            detail={
                "code": 40001 if "已存在" in str(e) else 50001,
                "msg": str(e),
                "data": None
            }
        )


@router.get("/{project_id}/export/zip", response_model=Dict[str, Any])
async def export_project(
    project_id: str,
    user_id: str = Depends(get_current_user_id)
):
    """导出项目为ZIP"""
    try:
        zip_path = await project_service.export_project(
            project_id=project_id,
            user_id=user_id,
            export_type="zip"
        )
        
        # 这里应该返回可下载的URL，暂时返回文件路径
        return {
            "code": 200,
            "msg": "导出成功",
            "data": {
                "zip_url": f"/downloads/{zip_path}",
                "expire_time": "2024-12-31 23:59:59"
            }
        }
    
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail={
                "code": 50001,
                "msg": f"项目导出失败: {str(e)}",
                "data": None
            }
        )
